package z.myServer;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Server {
	//创建一个ServerSocket，用于监听客户端Socket连接请求
	ServerSocket server = null;
	
	//装多个客户端的容器
	Collection clients = new ArrayList();
	
	public Server(int port) throws Exception {
		server = new ServerSocket(port);
	}
	
	//可接受多个客户端连接
	public void startServer() throws Exception {
		System.out.println("服务器启动中...");
		while (true) {
			//侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞
			Socket s = server.accept();
			
			clients.add(new ClientProcess(s));
			
			System.out.println("NewClient" + s.getInetAddress() + ":" + s.getPort());
			System.out.println("ClientCount: " + clients.size() + "\n");
			
		}
	}
	
	class ClientProcess implements Runnable {
		
		Socket s = null;
		
		public ClientProcess(Socket s) {
			this.s = s;
			//启动线程
			(new Thread(this)).start();
		}
		//发送消息给客户端
		public void send(String str) throws IOException {
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			dos.writeUTF(str);
//			OutputStream os = s.getOutputStream();
//            MessagePackage mp = new MessagePackage();
//            mp.setMessage(str);
//            os.write(mp.serialize());
		}
		//获取客户端发来的消息
//		public String getMessage() throws Exception {
//			DataInputStream dis = new DataInputStream(s.getInputStream());
//			String str = dis.readUTF();
//			return str;
//		}
		
		//释放socket并移除断开的客户端
		public void destory() {
			try {
				if (s != null) s.close();
				clients.remove(this);
				System.out.println("A client out!");
				System.out.println("ClientCount: " + clients.size() + "\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		//继续监听是否有消息发来
		public void run() {
			
			try {
				DataInputStream dis = new DataInputStream(s.getInputStream());
				//InputStream is = s.getInputStream();
				String str = null;
				
				while (true) {
					//没收到消息来该方法会阻塞
					str = dis.readUTF();
					System.out.println(s.getInetAddress() + "-" + s.getPort() + ": " + str);
					//消息共享到多个客户端
					for (Iterator it = clients.iterator(); it.hasNext();) {
						
						ClientProcess cp = (ClientProcess) it.next();
						
						if (this != cp) {
							cp.send(s.getInetAddress() + "-" + s.getPort() + ": " + str);
						}
						
					}
				}
				
			} catch (Exception e) {
				//客户端退出后触发
				System.out.println("Client quit");
				this.destory();
			}
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		Server st = new Server(9050);
		st.startServer();
	}
	
}

